local hanting = fk.CreateSkill{
  name = "pegasus__hanting",
  tags = { Skill.Wake },
}

local prompts = {}
prompts.refresh = "#pegasus__hanting-refresh"

Fk:loadTranslationTable{
  ["pegasus__hanting"] = "撼庭",
  [":pegasus__hanting"] = "觉醒技，准备阶段，若场上超过半数的技能已失效，你依次重置每名角色一个已失效的技能，若均为同名技能，你获得之。"
    .. "<br/><font color='grey'><small>耦：目前只能获得〖问道〗</small></font>",

  [prompts.refresh] = "撼庭：重置 %src 的一个已失效的技能",
}

local getWendao = function (player)
  local index = player.tag["pegasus__wendao"] or 1
  player.room:handleAddLoseSkills(player, "pegasus__wendao"..tostring(index))
  player.tag["pegasus__wendao"] = index + 1
end

---@param room Room
---@return number all
---@return number used
---@return table<integer, string[]> skills
local function getSkillsOnFild(room)
  local all, used = 0, 0
  local skills = {} ---@type table<integer, string[]>

  for _, p in ipairs(room.alive_players) do
    skills[p.id] = {}
    for _, skill in ipairs(p.player_skills) do
      if skill:isPlayerSkill(p) then
        all = all + 1
        if skill:hasTag(Skill.Limited) and p:usedSkillTimes(skill.name, Player.HistoryGame) == 1 then
          used = used + 1
          table.insert(skills[p.id], skill.name)
        end
      end
    end
  end

  return all, used, skills
end

hanting:addEffect(fk.EventPhaseStart, {
  can_wake = function (self, event, target, player, data)
    local all, used, _ = getSkillsOnFild(player.room)
    return used >= all / 2
  end,
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(hanting.name) and player == target and data.phase == Player.Start
      and player:usedSkillTimes(hanting.name, Player.HistoryGame) == 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local _, _, skills = getSkillsOnFild(room)
    local choices = {}

    for _, p in ipairs(room.alive_players) do
      if #skills[p.id] > 0 then
        local choice = room:askToChoice(player, {
          choices = skills[p.id],
          cancelable = false,
          detailed = true,
          prompt = prompts.refresh .. ":" .. p.id,
          skill_name = hanting.name,
        })

        player:setSkillUseHistory(choice, 0, Player.HistoryGame)
        table.insert(choices, choice)
      end
    end

    if #choices > 0 and table.every(choices, function (s) return string.startsWith(s, "pegasus__wendao") end) then
      getWendao(player)
    end
  end,
})

return hanting